package com.sso.core.filter;

import com.sso.core.path.impl.AntPathMatcher;
import com.sso.core.user.SsoUser;
import com.sso.core.conf.SSOConf;
import com.sso.core.entity.ReturnData;
import com.sso.core.login.SsoTokenLoginHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * app sso filter (api using)
 */
public class SsoTokenFilter extends HttpServlet implements Filter {
    private static Logger logger = LoggerFactory.getLogger(SsoTokenFilter.class);

    private static final AntPathMatcher antPathMatcher = new AntPathMatcher();

    private String ssoServer;
    private String logoutPath;
    private String excludedPaths;
    private String redirectUrl;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

        ssoServer = filterConfig.getInitParameter(SSOConf.SSO_SERVER);
        ssoServer = ssoServer.trim();
        if (ssoServer.endsWith("/")) {
            ssoServer = ssoServer.substring(0, ssoServer.length() - 1);
        }
        logoutPath = filterConfig.getInitParameter(SSOConf.SSO_LOGOUT_PATH);
        excludedPaths = filterConfig.getInitParameter(SSOConf.SSO_EXCLUDED_PATHS);
        redirectUrl = filterConfig.getInitParameter(SSOConf.REDIRECT_URL);

        logger.info("-----------MySsoTokenFilter init param ssoServer -> {}" , ssoServer);
        logger.info("-----------MySsoTokenFilter init param logoutPath -> {}" , logoutPath);
        logger.info("-----------MySsoTokenFilter init param excludedPaths -> {}" , excludedPaths);
        logger.info("-----------MySsoTokenFilter init param redirectUrl -> {}" , redirectUrl);

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        res.addHeader("Access-Control-Allow-Origin", "*");
        res.addHeader("Access-Control-Allow-Methods", "*");
        res.addHeader("Access-Control-Allow-Headers", "*");

        String servletPath = req.getServletPath();

        if (excludedPaths != null && excludedPaths.trim().length() > 0) {
            for (String excludedPath : excludedPaths.split(",")) {
                String uriPattern = excludedPath.trim();

                // ANT表达式
                if (antPathMatcher.match(uriPattern, servletPath)) {
                    // excluded path, allow
                    chain.doFilter(request, response);
                    return;
                }

            }
        }

        // logout filter
        if (logoutPath != null && logoutPath.trim().length() > 0 && logoutPath.equals(servletPath)) {

            SsoTokenLoginHelper.logout(req);
            res.setStatus(HttpServletResponse.SC_OK);
            res.setContentType("application/json;charset=UTF-8");
            res.getWriter().println("{\"code\":" + ReturnData.SUCCESS_CODE + ", \"msg\":\"\"}");

            return;
        }


        SsoUser seoUser = SsoTokenLoginHelper.loginCheck(req);
        if (seoUser == null) {
            res.setStatus(HttpServletResponse.SC_OK);
            res.setContentType("application/json;charset=UTF-8");
            res.getWriter().println("{\"code\":" + SSOConf.SSO_LOGIN_FAIL_RESULT.getCode() + ", \"msg\":\"" + SSOConf.SSO_LOGIN_FAIL_RESULT.getMsg() + "\",\"ssoUrl\":\"" + ssoServer + SSOConf.SSO_LOGIN + "?" + SSOConf.REDIRECT_URL + "=" + redirectUrl + "\"}");
            return;
        }

        request.setAttribute(SSOConf.SSO_USER, seoUser);
        chain.doFilter(request, response);
        return;
    }


}
